"""
Case Type   : SQL语法
Case Name   : 兼容PG/B模式下创建函数
Create At   : 2023/02/15
Owner       : cr13
Description :
    1.创建兼容PG/B模式数据库
    2.分别在兼容PG/B模式数据库下创建函数
    3.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
History     :
"""

import os
import unittest
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SQL(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.commsh = CommonSH('PrimaryDbUser')
        self.database1 = 'd_ddl_create_function_0160_01'
        self.database2 = 'd_ddl_create_function_0160_02'
        self.function = 'f_ddl_create_function_0160'

    def test_ddl_function(self):
        text = "----step1:创建兼容PG/B模式数据库 expect:成功----"
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.database1};drop database " \
            f"if exists {self.database2};create database {self.database1} " \
            f"dbcompatibility = 'PG';create database {self.database2} " \
            f"dbcompatibility = 'B';"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertEqual(result.count(self.constant.DROP_DATABASE_SUCCESS), 2,
                         '执行失败' + text)
        self.assertEqual(result.count(self.constant.CREATE_DATABASE_SUCCESS),
                         2, '执行失败' + text)

        text = "----step2:分别在兼容PG/B模式数据库下创建函数 expect:成功----"
        self.log.info(text)
        sql_cmd = f"create or replace function {self.function} (v int[]) " \
            f"return int as " \
            f"n int;" \
            f"begin" \
            f"    n := v();" \
            f"    return n;" \
            f"end;"
        result = self.commsh.execut_db_sql(sql_cmd, dbname=self.database1)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, result,
                      '执行失败' + text)
        result = self.commsh.execut_db_sql(sql_cmd, dbname=self.database2)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_FUNCTION_SUCCESS_MSG, result,
                      '执行失败' + text)

    def tearDown(self):
        text = '-----step3:清理环境 expect:成功-----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.database1};drop database " \
            f"if exists {self.database2};"
        result = self.commsh.execut_db_sql(sql_cmd)
        self.log.info(result)
        self.assertEqual(result.count(self.constant.DROP_DATABASE_SUCCESS), 2,
                         '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
